package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import javax.swing.JFileChooser;

/**
 * Classe que cria uma janela para o usuario escolher um arquivo e o colocar
 * no sistema.
 * @author Jean Vasconcelos, Carla Sukeyosi, Matheus Emanuel, Heitor Carvalho
 */
public class ArchiveSelector extends JFileChooser
{
    private String filePath;
    private String oldImagePath;

    public ArchiveSelector() throws Exception
    {
        int result = this.showOpenDialog( null );

        if ( result == JFileChooser.APPROVE_OPTION )
         {
            URL mediaURL = null;
            String path = null;
            
            try
            {
                mediaURL = this.getSelectedFile().toURI().toURL();
                path = this.getSelectedFile().toURI().toURL().toString();
            }
            catch ( MalformedURLException malformedURLException )
            {
                System.err.println( "Erro ao tentar criar URL." );
            }
            
            if ( mediaURL != null )
            {
                String destiny = "src" + File.separator + "com" + File.separator
            + "files" + File.separator;
                
                String fileName = null;

                 if (path.contains(File.separator))
                     fileName = path.substring(path.lastIndexOf(File.separator));
                 else if (path.contains(File.pathSeparator))
                     fileName = path.substring(path.lastIndexOf(File.pathSeparator));
                 else if (path.contains("/"))
                     fileName = path.substring(path.lastIndexOf("/"));
                 else
                 {
                     System.out.println("Erro ao tentar copiar arquivo");
                     return;
                 }
                 if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")
                    || path.endsWith(".bmp") || path.endsWith(".gif"))
                 {
                     destiny += "images" + File.separator;
                     try 
                     {
                         File file = new File(destiny + fileName);
                         if (oldImagePath != null)
                         {
                             File deleteFile = new File(oldImagePath);
                             deleteFile.delete();
                         }
                         this.filePath = destiny + fileName;
                     } catch (Exception ex)
                     {
                         System.out.println(ex.getMessage());
                     }
                 } 
                 } else
                 {
                     throw new Exception ("Arquivo invalido.");
                 }
                 try 
                 {
                     FileInputStream fis = new FileInputStream(new File(mediaURL.toURI()));
                     FileOutputStream fos = new FileOutputStream(new File(this.filePath));
                     FileChannel destinyFC;
                     
                    FileChannel sourceFC = fis.getChannel();
                    destinyFC = fos.getChannel();
                    sourceFC.transferTo(0, sourceFC.size(), destinyFC);
                    
                     destinyFC.close();
                 } catch (Exception ex)
                 {
                        System.out.println(ex.getMessage());
                 }
            }
    }
    
    /**
     * Recupera o caminho que o usurio escolheu
     * @return caminho do arquivo que o usuario escolheu
     */
    public String getFilePath() 
    {
        return filePath;
    }

    public void setOldPath(String imagePath) 
    {
        this.oldImagePath = imagePath;
    }
}

